<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <ul>
        <li><router-link to="/">Home</router-link></li>
        <li><router-link to="/user/1">User/1</router-link></li>
        <li><router-link to="/user/2">User/2</router-link></li>
      </ul>
      <router-view></router-view>
    </div>
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router@3/dist/vue-router.js"></script>
    <script>
      const Home = {template:'<div>Home</div>'}
      const User = {
        props:['userId'],
        template:`<div>userId:{{userId}}</div>`
      }
      const Profile = {template:'<div>Profile</div>'}
      var routes = [
        {name:'home',path:'/',component:Home},
        {
            path:"/user/:userId",
            component:User,
            props:true
        },
        {name:'profile',path:'/profile',component:Profile},
      ];
      Vue.use(VueRouter);
      var router = new VueRouter({routes});
      var vm = new Vue({
        el: "#app",
        router,
      });
      //监听跳转错误，进行全局捕获
      router.onError((error)=>{
        console.error(error)
      });
      //每一次导航前都会触发,全局的，针对所有的路径跳转都会生效
      router.beforeEach((to,from,next)=>{
        console.log('beforeEach1',to.path)
        next();//如果后面还有钩子，就调用下一个钩子
      });
      router.beforeEach((to,from,next)=>{
        console.log('beforeEach2',to.path)
        //如果后面没有钩子了，就真正进行跳转了
        //next方法可以接收参数
        //如果传的是布尔值,则不再跳转了，如果路径已经改变了，还会变回去
        //next(false);
        //还可以传新的路径
        //用户未登录跳到登录页，如果已经登录就可以继续访问
        //next('/profile');
        //next({name:'profile'});
        //next(new Error('未登录'));
        next();
      });
      router.afterEach((to,from)=>{
        console.log('afterEach1',to.path)
      });
      router.afterEach((to,from)=>{
        console.log('afterEach2',to.path)
      });
    </script>
  </body>
</html>
